/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file   fatfs.c
  * @brief  Code for fatfs applications
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
#include <stdio.h>
#include "fatfs.h"

uint8_t retSD;    /* Return value for SD */
char SDPath[4];   /* SD logical drive path */
FATFS SDFatFS;    /* File system object for SD logical drive */
FIL SDFile;       /* File object for SD */

/* USER CODE BEGIN Variables */
#include "string.h"

FRESULT fserr[7];
uint32_t bytes_written, bytes_read;
uint8_t w_text[] = "SDCard test. \r\n";
uint8_t r_text[100];
/* USER CODE END Variables */

void MX_FATFS_Init(void)
{
  /*## FatFS: Link the SD driver ###########################*/
  retSD = FATFS_LinkDriver(&SD_Driver, SDPath);

  /* USER CODE BEGIN Init */
  /* additional user code for init */
    if ((fserr[0] = f_mount(&SDFatFS, SDPath, 0)) == FR_OK)
        // write
        if ((fserr[1] = f_open(&SDFile, "STM32.txt", FA_CREATE_ALWAYS | FA_WRITE)) == FR_OK)
            if ((fserr[2] = f_write(&SDFile, w_text, sizeof(w_text), (void *) &bytes_written)) == FR_OK)
                if ((fserr[3] = f_close(&SDFile)) == FR_OK)
                    // read
                    if ((fserr[4] = f_open(&SDFile, "STM32.txt", FA_READ)) == FR_OK)
                        if ((fserr[5] = f_read(&SDFile, r_text, sizeof(r_text), (void *) &bytes_read)) == FR_OK)
                            if ((fserr[6] = f_close(&SDFile)) == FR_OK)
                                if (!strcmp((char *) r_text, (char *) w_text)) printf("fatfs success\n");

  /* USER CODE END Init */
}

/**
  * @brief  Gets Time from RTC
  * @param  None
  * @retval Time in DWORD
  */
DWORD get_fattime(void)
{
  /* USER CODE BEGIN get_fattime */
  return 0;
  /* USER CODE END get_fattime */
}

/* USER CODE BEGIN Application */

/* USER CODE END Application */
